package com.pro01.backend.service;

import com.pro01.backend.mapper.ForumPostLikeMapper;
import com.pro01.backend.mapper.ForumPostMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ForumPostLikeService {

    @Autowired
    private ForumPostLikeMapper forumPostLikeMapper;

    @Autowired
    private ForumPostMapper forumPostMapper;

    @Autowired
    private PointService pointService;

    // 点赞
    public void likePost(Long userId, Long postId) {
        // 先判断是否已经点过赞
        if (forumPostLikeMapper.hasLiked(userId, postId) > 0) {
            throw new RuntimeException("你已经点赞过该帖子");
        }

        // 插入点赞记录
        forumPostLikeMapper.insertLike(userId, postId);

        // 帖子点赞数 +1
        forumPostMapper.incrementLikeCount(postId);

        // ✅ 被点赞人加积分（不是自己）
        Long postOwnerId = forumPostMapper.getPostOwnerId(postId);
        if (!userId.equals(postOwnerId)) {
            pointService.addLikeReward(postOwnerId);
        }
    }

    // 取消点赞
    public void unlikePost(Long userId, Long postId) {
        if (forumPostLikeMapper.hasLiked(userId, postId) == 0) {
            throw new RuntimeException("你还没有点赞该帖子");
        }

        forumPostLikeMapper.deleteLike(userId, postId);
        forumPostMapper.decrementLikeCount(postId);
    }

}
